<template>
  <d2-container>
    <template slot="header">
      <el-form
        :inline="true"
        :model="queryForm"
        ref="queryForm"
        size="mini"
        style="margin-bottom: -18px;"
      >
        <el-form-item label="区域编号" prop="areaName">
          <el-input v-model="queryForm.meterName" placeholder="区域编号" style="width: 100px;" />
        </el-form-item>

        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="queryForm.meterModel" placeholder="区域名称" style="width: 100px;" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFormSubmit">
            <d2-icon name="search" />查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <split-pane :min-percent="10" :max-percent="20" :default-percent="20" split="vertical">
      <template slot="paneL">
        <div
          @click="addAreaBoxShow = true"
          class="add-area-box"
          style="position: absolute;right: 10px;z-index: 999;cursor: pointer"
        >
          <i class="el-icon-document-add" style="font-size: 24px;"></i>
        </div>
        <my-area-tree @change="onAreaChange" />
      </template>
      <template slot="paneR">
        <d2-crud
          ref="d2Crud"
          selection-row
          @selection-change="handleSelectionChange"
          add-title="添加"
          :add-template="addTemplate"
          :add-rules="addRules"
          @row-add="handleRowAdd"
          :columns="columns"
          :data="data"
          :loading="loading"
          :pagination="pagination"
          @pagination-current-change="paginationCurrentChange"
          @dialog-open="handleDialogOpen"
          @dialog-cancel="handleDialogCancel"
          :form-options="formOptions"
          edit-title="修改"
          :edit-template="addTemplate"
          :edit-rules="addRules"
          :rowHandle="rowHandle"
          @row-edit="handleRowEdit"
          @row-remove="handleRowRemove"
        >
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="deleteRows">删除</el-button>
        </d2-crud>
      </template>
    </split-pane>
    <el-dialog :visible.sync="addAreaBoxShow" v-if="addAreaBoxShow" title="添加">
      <div class="demo-input-suffix" style="width: 50%;display: inline-block;margin-bottom: 10px;">
        区域编号：
        <el-input placeholder="请输入内容" :disabled="true" style="width: 200px"></el-input>
      </div>
      <div class="demo-input-suffix" style="width: 50%;display: inline-block;margin-bottom: 10px;">
        区域名称：
        <el-input placeholder="请输入内容" :disabled="true" style="width: 200px"></el-input>
      </div>
      <div class="demo-input-suffix" style="width: 50%;display: inline-block;margin-bottom: 10px;">
        是否日结：
        <el-input placeholder="请输入内容" :disabled="true" style="width: 200px"></el-input>
      </div>
      <div class="demo-input-suffix" style="width: 50%;display: inline-block;margin-bottom: 10px;">
        月结算日：
        <el-input placeholder="请输入内容" :disabled="true" style="width: 200px"></el-input>
      </div>
      <div class="demo-input-suffix" style="width: 50%;display: inline-block;margin-bottom: 10px;">
        是否发送短信：
        <el-input placeholder="请输入内容" :disabled="true" style="width: 200px"></el-input>
      </div>
      <div class="demo-input-suffix" style="width: 100%;margin-bottom: 20px;">
        拆表备注 ：
        <el-input
          type="textarea"
          style="width: 92%"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
        ></el-input>
      </div>
      <div class="btn-box" style="width: 92%; text-align: right; padding-right: 20px">
        <el-button type="primary">保存</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import MyAreaTree from "@/components/my-area-tree";
import Bus from "@/eventBus/bus";

import dayjs from "dayjs";

export default {
  name: "household",
  components: { MyAreaTree },

  data() {
    return {
      addAreaBoxShow: false,
      archive: null,
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 100,
        total: 0
      },
      rowHandle: {
        columnHeader: "操作",
        edit: {
          text: "编辑"
        },
        remove: {
          text: "删除"
        }
      },
      queryForm: {
        areaId: "1",
        areaName: "中国",
        meterName: "", // 区域编号
        meterModel: "" // 区域名称
      },
      columns: [
        {
          title: "区域编号",
          key: "areaSerialnumber",
          sortable: true
        },
        {
          title: "区域名称",
          key: "name",
          sortable: true
        },
        {
          title: "负责人",
          key: "areaContactName",
          sortable: true
        },
        {
          title: "手机",
          key: "areaContactPhone",
          sortable: true
        },
        {
          title: "是否发送短信",
          key: "isSendSmsName",
          sortable: true
        },
        {
          title: "是否日结",
          key: "isDaySettlementName",
          sortable: true
        },
        {
          title: "月结算日",
          key: "settlementDay",
          sortable: true
        }
      ],
      addRules: {
        name: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        isDaySettlement: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        settlementDay: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        isSendSms: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ],
        areaSerialnumber: [
          {
            required: true,
            message: "必填",
            trigger: "blur"
          }
        ]
      },
      addTemplate: {
        areaSerialnumber: {
          title: "区域编号",
          value: "",
          component: {
            disabled: true
          }
        },
        name: {
          title: "区域名称",
          value: ""
        },
        parentId: {
          title: "上级区域Id",
          value: "",
          component: {
            disabled: true,
            show:false
          }
        },
        parentName: {
          title: "上级区域",
          value: "",
          component: {
            disabled: true
          }
        },
        isDaySettlement: {
          title: "是否日结",
          value: "",
          component: {
            name: "el-select",
            options: []
          }
        },
        settlementDay: {
          title: "月结算日",
          value: "",
          component: {
            name: "el-select",
            options: []
          }
        },
        isSendSms: {
          title: "是否发送短信",
          value: "",
          component: {
            name: "el-select",
            options: []
          }
        },
        areaContactName: {
          title: "负责人",
          value: ""
        },
        areaContactPhone: {
          title: "手机",
          value: ""
        },
        areaContactTel: {
          title: "固话",
          value: ""
        },
        areaContactMail: {
          title: "邮件",
          value: ""
        },
        areaMapLongitude: {
          title: "经度",
          value: ""
        },
        areaMapLatitude: {
          title: "纬度",
          value: ""
        }
      },
      data: [],
      treeData: [],
      values: [],
      treeParams: {
        "default-expand-all": true,
        data: [],
        props: {
          children: "children",
          label: "name",
          value: "id"
        }
      },
      formOptions: {
        labelWidth: "80px",
        labelPosition: "left",
        saveLoading: false
      },
      selectArea: {
        parentId: "1",
        parentName: "中国"
      }
    };
  },
  mounted() {
    this.getEquipmentType();
    this.fetchData();
  },
  methods: {
    handleDialogOpen({ mode, row, index }) {
      if (mode === "edit") {
        this.$api.admin_area_get({ id: row.id }).then(res => {
          const data = JSON.parse(JSON.stringify(res));
          this.$refs.d2Crud.setFormData(data);
        });
      } else {
         this.addTemplate.parentId.value = this.selectArea.parentId;
         this.addTemplate.parentName.value = this.selectArea.parentName;
      }
    },
    // 关闭弹框
    handleDialogCancel(done) {
      done();
    },
    // 分页操作
    paginationCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.fetchData();
    },
    onAreaChange(data, node) {
      this.queryForm.areaId = data.id;
      this.queryForm.areaName = data.name;
      this.selectArea.parentId = data.id;
      this.selectArea.parentName = data.name;
      this.fetchData();
    },
    handleSelectionChange(selection) {
      this.selectionRow = selection;
    },
    fetchData() {
      this.loading = true;
      this.$api
        .admin_area_getPageList({
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          areaOrg: this.queryForm.areaId,
          ...this.queryForm
        })
        .then(res => {
          this.data = res.data;
          this.pagination.total = res.total;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 新增数据
    addRow() {
      this.$refs.d2Crud.showDialog({
        mode: "add"
      });
    },
    handleRowEdit(row, done) {
      const params = JSON.parse(JSON.stringify(row.row));
      this.formOptions.saveLoading = true;
      this.$api
        .admin_area_update(params)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          done();
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    handleRowRemove({ index, row }, done) {
      this.$api.admin_area_delete([row.id]).then(res => {
        this.$message({
          message: "删除成功",
          type: "success"
        });
        this.fetchData();
        done();
      });
    },
    deleteRows() {
      this.$confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(() => {
        this.$api
          .admin_area_delete(this.selectionRow.map(item => item.id))
          .then(res => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.fetchData();
          });
      });
    },
    handleRowAdd(row, done) {
      const params = JSON.parse(JSON.stringify(row));
      this.formOptions.admin_area_add = true;
      this.$api
        .admin_area_add(params)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          done();
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    // 获取查询枚举
    getEquipmentType() {
      this.$api
        .admin_area_getEquipmentType()
        .then(res => {
          const yesOrNo = res.yesOrNo.map(y => {
            return {
              value: y.value,
              label: y.valueName
            };
          });
          this.addTemplate.isDaySettlement.component.options = yesOrNo;
          this.addTemplate.isSendSms.component.options = yesOrNo;
          const settlementDay = res.settlementDay.map(s => {
            return {
              value: s.value,
              label: s.value
            };
          });
          this.addTemplate.settlementDay.component.options = settlementDay;
          const areaSerialnumber = "AREA" + new Date().getTime();
          this.addTemplate.areaSerialnumber.value = areaSerialnumber;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {});
    },
    handleFormSubmit() {
      this.pagination.currentPage = 1;
      this.fetchData();
      Bus.$emit('reInitTree', "");
    }
  }
};
</script>
